package com.cl.park.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.cl.park.util.HibernateUtil;
import com.cl.park.util.PageUtil;

@SuppressWarnings("unchecked")
public class BaseDaoImpl implements BaseDao{

	/**
	 * 添加
	 * @param obj
	 */
	public void add(Object obj) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.save(obj);
			tx.commit();

		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			System.out.println(e);
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 删除
	 * @param obj
	 */
	public void delete(Object obj) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.delete(obj);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 根据主键删除
	 * @param clazz
	 * @param id
	 */
	@SuppressWarnings("null")
	public void deleteById(Class clazz, Serializable id) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			session.delete(session.get(clazz, id));
			tx.commit();
		} catch (Exception e) {
			System.out.println(e);
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 修改
	 * @param obj
	 */
	public void update(Object obj) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.update(obj);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			System.out.println(e);
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 根据主键查询
	 * @param clazz
	 * @param id
	 * @return
	 */
	public Object get(Class clazz, Serializable id) {
		Session session = null;

		try {
			session = HibernateUtil.getSession();
			Object obj = session.get(clazz, id);
			return obj;
		}finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 根据多个属性查询
	 * @param clazz
	 * @param strs
	 * @return
	 */
	public Object getByNProperty(Class clazz, String... strs) {

		if (strs != null && strs.length != 0 && 0 == strs.length % 2) {
			StringBuffer hql = new StringBuffer("select model from "
					+ clazz.getName() + " as model where ");
			for (int i = 0; i < strs.length; i += 2) {
				if(strs[i+1]==null || strs[i+1].equals("")){
					continue;
				}
				hql.append(" model." + strs[i] + " = '" + strs[i + 1] + "' and");
			}
			hql.append(" 1=1");
			Session session = null;
			try {
				session = HibernateUtil.getSession();
				System.out.println(hql.toString());
				List<Object> objs = session.createQuery(hql.toString()).list();
				if (objs != null && objs.size() != 0) {
					return objs.get(0);
				} else {
					return null;
				}
			} finally {
				if (session != null) {
					session.close();
				}
			}
		} else {
			return null;
		}

	}

	/**
	 * 根据属性查询
	 * @param clazz
	 * @param pName
	 * @param pValue
	 * @return
	 */
	public Object getUniqueByProperty(Class clazz, String pName, Object pValue) {
		Session session = null;

		try {
			session = HibernateUtil.getSession();
			String hql = "select model from " + clazz.getName()
					+ " as model where model." + pName + " = '" + pValue + "'";
			List<Object> objs = session.createQuery(hql).list();
			if (objs != null && objs.size() != 0) {
				return objs.get(0);
			} else {
				return null;
			}

		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 根据HQL查询
	 * @param hql
	 * @return
	 */
	public Object getUniqueByHql(String hql) {

		Session session = null;

		try {
			session = HibernateUtil.getSession();
			List<Object> objs = session.createQuery(hql).list();
			if (objs != null && objs.size() != 0) {
				return objs.get(0);
			} else {
				return null;
			}

		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 根据SQL查询
	 * @param sql
	 * @param clazz
	 * @return
	 */
	public Object getUniqueBySql(String sql, Class clazz) {

		Session session = null;

		try {
			session = HibernateUtil.getSession();
			Query query = session.createSQLQuery(sql).addEntity(clazz);
			List<Object> objs = query.list();
			if (objs != null && objs.size() != 0) {
				return objs.get(0);
			} else {
				return null;
			}
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	// ////////////////////查询单个完毕////////////////

	/**
	 * 查询所有
	 */
	public List<Object> getList(Class clazz) {
		Session session = null;

		try {
			session = HibernateUtil.getSession();
			String hql = "select model from " + clazz.getName() + " as model ";
			List list = session.createQuery(hql).list();
			return list;
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 根据属性查询 全部
	 * @param clazz
	 * @param pName
	 * @param pValue
	 * @return
	 */
	public List<Object> getListByProperty(Class clazz, String pName,
			Object pValue) {
		Session session = null;

		try {
			session = HibernateUtil.getSession(); // 获得安全session
			String hql = "select model from " + clazz.getName()
					+ " as model where model." + pName + " = '" + pValue + "'";
			return session.createQuery(hql).list();

		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 根据属性和条件查询 全部
	 * @param clazz	类
	 * @param pName	属性名称
	 * @param pValue 属性值	
	 * @param condition 符号
	 * @return 集合
	 */
	public List<Object> getListByProperty(Class clazz, String pName,
			Object pValue, String condition) {
		Session session = null;

		try {
			session = HibernateUtil.getSession();
			String hql = "select model from " + clazz.getName()
					+ " as model where model." + pName + " " + condition
					+ " '%" + pValue + "%'";
			List<Object> list = session.createQuery(hql).list();
			return list;
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 根据多个属性模糊查询
	 * @param clazz 类
	 * @param strs 【1属性名2值3属性4值】
	 * @return
	 */
	public List getListByNProperty(Class clazz, String... strs) {

		if (strs != null && strs.length != 0 && 0 != strs.length % 2) {
			StringBuffer hql = new StringBuffer("select model from "
					+ clazz.getName() + " as model where ");
			for (int i = 0; i < strs.length; i += 2) {
				hql.append(" " + strs[i] + " Like  %" + strs[i + 1] + "% ");
			}

			Session session = null;
			try {
				session = HibernateUtil.getSession();
				List<Object> objs = session.createQuery(hql.toString()).list();
				return objs;
			} finally {
				if (session != null) {
					session.close();
				}
			}
		} else {
			return null;
		}

	}

	/**
	 * 根据HQL查询 全部
	 * @param hql
	 * @return
	 */
	public List<Object> getListByHql(String hql) {

		Session session = null;

		try {
			session = HibernateUtil.getSession();
			List list = session.createQuery(hql).list();
			return list;

		} catch (Exception e) {
			System.out.println(e);
		}finally {
			if (session != null) {
				session.close();
			}
		}
		return null;
	}

	/**
	 * 根据SQL查询全部
	 * @param sql
	 * @param clazz
	 * @return
	 */
	public List getListBySql(String sql, Class clazz) {

		Session session = null;

		try {
			session = HibernateUtil.getSession();
			Query query = session.createSQLQuery(sql).addEntity(clazz);
			return query.list();
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}


	/**
	 * 根据HQL分页查询
	 * @param hql
	 * @param pageUtil
	 */
	public void getListByPage(String hql, PageUtil pageUtil) {
		if (null == hql) {
			return;
		}
		Session session = null;

		try {
			session = HibernateUtil.getSession();
			if(pageUtil.getOrderBy()!=null && !pageUtil.getOrderBy().equals("")){
				hql +=" ORDER BY "+pageUtil.getOrderBy() +" "+pageUtil.getSort();
			}
			Query query = session.createQuery(hql);
			query.setFirstResult(pageUtil.getFirstRec());
			query.setMaxResults(pageUtil.getPageSize());
			pageUtil.setList(query.list());
			String queryString = "";
			if (hql.toUpperCase().indexOf("SELECT") != -1) {
				int i = query.getQueryString().toUpperCase().indexOf("FROM");
				queryString = "Select count(*) "
						+ hql.substring(i, hql.length());
			} else {
				queryString = "Select count(*) " + hql;
			}
			// 去掉ORDER BY 的部分
			int j = queryString.toUpperCase().lastIndexOf("ORDER");
			if (j != -1) {
				queryString = queryString.substring(0, j);
			}
			Query cquery = session.createQuery(queryString);
			cquery.setCacheable(true);
			Number recTotal = ((Number) cquery.iterate().next()).intValue();
			pageUtil.setRecTotal(recTotal.intValue());
		} catch (Exception e) {
			System.out.println(e);
		}finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/**
	 * 根据多个属性模糊查询
	 * @param clazz 类
	 * @param strs 【1属性名2值3属性4值】
	 * @return
	 */
	public void getListByNProperty(Class clazz,PageUtil pageUtil, String... strs) {
		StringBuffer hql=null;
		if (strs != null && strs.length != 0 && 0 != strs.length % 2) {
				hql = new StringBuffer("select model from "
					+ clazz.getName() + " as model where ");
			for (int i = 0; i < strs.length; i += 2) {
				if(strs[i + 1]==null||strs[i + 1].equals("")){
					continue;
				}
				hql.append(" " + strs[i] + " Like  %" + strs[i + 1] + "% ");
			}

			Session session = null;
			try {
				session = HibernateUtil.getSession();
				Query query = session.createQuery(hql.toString());
				query.setFirstResult(pageUtil.getFirstRec());
				query.setMaxResults(pageUtil.getPageSize());
				pageUtil.setList(query.list());
				String queryString = "";
				if (hql.toString().toUpperCase().indexOf("SELECT") != -1) {
					int i = query.getQueryString().toUpperCase().indexOf("FROM");
					queryString = "Select count(*) "
							+ hql.substring(i, hql.length());
				} else {
					queryString = "Select count(*) " + hql;
				}
				Query cquery = session.createQuery(queryString);
				cquery.setCacheable(true);
				int recTotal = ((Integer) cquery.iterate().next()).intValue();
				pageUtil.setRecTotal(recTotal);

			} finally {
				if (session != null) {
					session.close();
				}
			}
		}

	}
	/**
	 * 执行HQL
	 * @param hql
	 * @return
	 */
	public void doHqlForList(String hql,PageUtil pageUtil){
			Session session = null;
			try {
				session = HibernateUtil.getSession();
				Query query = session.createQuery(hql);
				query.setFirstResult(pageUtil.getFirstRec());
				query.setMaxResults(pageUtil.getPageSize());
				pageUtil.setList(query.list());
				String queryString = "";
				if (hql.toString().toUpperCase().indexOf("SELECT") != -1) {
					int i = query.getQueryString().toUpperCase().indexOf("FROM");
					queryString = "Select count(*) "
							+ hql.substring(i, hql.length());
				} else {
					queryString = "Select count(*) " + hql;
				}
				Query cquery = session.createQuery(queryString);
				cquery.setCacheable(true);
				int recTotal = ((Integer) cquery.iterate().next()).intValue();
				pageUtil.setRecTotal(recTotal);

			} finally {
				if (session != null) {
					session.close();
				}
			}
			
	}
	/**
	 * 执行单一查询的HQL语句
	 * @param hql
	 * @return
	 */
	public Object doHqlForOne(String hql){
		Session session = null;
		Object obj = null;
		try {
			session = HibernateUtil.getSession();
			Query query = session.createQuery(hql);
			obj = query.uniqueResult();
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return obj;
	}
	
	/**
	 * 根据HQL更新
	 * @param hql
	 * @return
	 */
	public Integer updateUniqueByHql(String hql) {

		Session session = null;

		try {
			session = HibernateUtil.getSession();
			Integer count = session.createQuery(hql).executeUpdate();
			return count;
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return null;
	}
	/**
	 * 分页查询全部
	 * @param calzz
	 * @param pageUtil
	 */
	public void getListByPage(Class calzz, PageUtil pageUtil) {
		String hql = "SELECT model from " + calzz.getName() + " as model";
		getListByPage(hql, pageUtil);
	}

	/**
	 * 根据HQL分页查询(new)
	 * @param hql
	 * @param pageUtil
	 */
	public void getNewListByPage(String hql, PageUtil pageUtil) {
		if (null == hql) {
			return;
		}
		Session session = null;

		try {
			session = HibernateUtil.getSession();
			Query query = session.createQuery(hql);
			query.setFirstResult(pageUtil.getFirstRec());
			query.setMaxResults(pageUtil.getPageSize());
			pageUtil.setList(query.list());
			String queryString = "";
			if (hql.toUpperCase().indexOf("SELECT") != -1) {
				int i = query.getQueryString().toUpperCase().indexOf("FROM");
				queryString = "Select count(*) "
						+ hql.substring(i, hql.length());
			} else {
				queryString = "Select count(*) " + hql;
			}
			// 去掉ORDER BY 的部分
			int j = queryString.toUpperCase().lastIndexOf("ORDER");
			if (j != -1) {
				queryString = queryString.substring(0, j);
			}
			Query cquery = session.createQuery(queryString);
			cquery.setCacheable(true);
			Number num = ((Number) cquery.iterate().next());
			pageUtil.setRecTotal(num.intValue());
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}finally {
			if (session != null) {
				session.close();
			}
		}
	}
	/**
	 *根据hql删除 
	 * 
	 */
	public Integer delUniqueByHql(String hql) {

		Session session = null;

		try {
			session = HibernateUtil.getSession();
			int count = session.createQuery(hql).executeUpdate();
			session.beginTransaction().commit();
			return count;
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return null;
	}
}
